package com.code.bolg.service.impl;

import com.code.bolg.bean.Article;
import com.code.bolg.enums.ResultEnum;
import com.code.bolg.exception.BolgExcetion;
import com.code.bolg.repository.ArticleRepository;
import com.code.bolg.service.ArticleService;
import com.code.bolg.utils.ApiReturnUtil;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public Article save(Article article) {
        Article save = articleRepository.save(article);
        return save;
    }

    @Override
    public int deleteById(int id) {

        Optional<Article> optional=articleRepository.findById(id);
        if(optional.isPresent()){
            articleRepository.deleteById(id);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public Article findById(int id) {
        Optional<Article> optional = articleRepository.findById(id);
        if (optional.isPresent()) {
            Article article = optional.get();
            return article;
        } else {
            throw new BolgExcetion(ResultEnum.NOTFINDDATA);
        }
    }

    @Override
    public List<Article> findAll(Article article,int pageNumber,int pageSize) {
        //分页构造
        Pageable pageable = PageRequest.of(pageNumber,pageSize);
        Page<Article> all = articleRepository.findAll( pageable);
        return  all.getContent();
    }
}
